package org.van.carfimodulesproduction.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.van.carfi.common.kernel.constant.LogActions;
import org.van.carfi.common.kernel.constant.WebConst;
import org.van.carfi.common.kernel.utils.APIResponse;
import org.van.carfi.common.kernel.utils.GsonUtils;
import org.van.carfimodulesproduction.model.UserDomain;
import org.van.carfimodulesproduction.service.log.LogService;
import org.van.carfimodulesproduction.service.user.UserService;
import org.van.carfimodulesproduction.utils.TaleUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/production")
public class StockController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @RequestMapping("hello-financial")
    @ResponseBody
    public String say(){
        return "HelloFinancial";
    }

    @PostMapping(value = "/getStock",  consumes= MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public APIResponse<?> toLogin(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody String body) {
        Map<String, String> map = GsonUtils.getMapFromJson(body, HashMap.class);
        String userAccount = map.get("userAccount");
        String password = map.get("password");
        Integer error_count = cache.get("login_error_count");
        try {
            UserDomain userInfo = userService.login(userAccount, password);
            request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, userInfo);
            // 设置cookie标识已登录
            TaleUtils.setCookie(response, userInfo.getUid());
            response.addCookie(new Cookie("failure_time",
                    String.valueOf(System.currentTimeMillis()/1000000+20000)));
            logService.addLog(LogActions.LOGIN.getAction(), userInfo.getUname() + "User", request.getRemoteAddr(),
                    userInfo.getUid());
        } catch (Exception e) {
            return APIResponse.fail(e.toString());
        }
        return APIResponse.success();
    }
}